﻿using BootstrapBlazor.Components;
using Messhall.UI.Permission.Model;
using Microsoft.AspNetCore.Components;
using Microsoft.Extensions.Localization;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Threading.Tasks;
using Messhall.Application.Dto.Users.Requests;
using Messhall.Application.Dto.Users.Responses;
using Messhall.Framework.Converts;
using Messhall.HostService.Interface.Permission;
using Messhall.HostService.Proxy;

namespace Messhall.UI.Permission.Pages.Users
{
    public partial class List
    {
        private readonly IUsers _usersService = ServiceFactory.Create<IUsers>();

        private static readonly
            ConcurrentDictionary<Type, Func<IEnumerable<UserListModel>, string, SortOrder, IEnumerable<UserListModel>>>
            SortLambdaCache = new();

        private UserListModel SearchModel { get; set; } = new UserListModel();

        private static IEnumerable<int> PageItemsSource => new int[] { 20, 50, 100 };

        [NotNull] private List<UserListModel>? Items { get; set; }

        /// <summary>
        /// OnInitialized 方法
        /// </summary>
        protected override async Task OnInitializedAsync()
        {
            await this.PagingAsync();
            await base.OnInitializedAsync();
        }

        private static Task<UserListModel> OnAddAsync() =>
            Task.FromResult(new UserListModel() { CreateTime = DateTime.Now });

        /// <summary>
        /// 保存用户信息
        /// </summary>
        /// <param name="item"></param>
        /// <param name="changedType"></param>
        /// <returns></returns>
        private async Task<bool> OnSaveAsync(UserListModel item, ItemChangedType changedType)
        {
            if (changedType == ItemChangedType.Add)
            {
                await this.CreateAsync(item);
            }
            else
            {
                await this.UpdateAsync(item);
            }
            
            await this.PagingAsync();

            return true;
        }

        private async Task<bool> OnDeleteAsync(IEnumerable<UserListModel> items)
        {
            var keyIds = items.Select(item => item.KeyId).ToArray();

            await this.RemoveAsync(keyIds);
            await this.PagingAsync();

            return true;
        }

        private static Task OnResetSearchAsync(UserListModel item)
        {
            item.Name = "";
            return Task.CompletedTask;
        }

        private Task<QueryData<UserListModel>> OnQueryAsync(QueryPageOptions options)
        {
            IEnumerable<UserListModel> items = Items;

            // 处理高级搜索
            if (!string.IsNullOrEmpty(SearchModel.Name))
            {
                items = items.Where(item =>
                    item.Name?.Contains(SearchModel.Name, StringComparison.OrdinalIgnoreCase) ?? false);
            }

            if (!string.IsNullOrEmpty(SearchModel.Name))
            {
                //items = items.Where(item => item.)?.Contains(SearchModel.), StringComparison.OrdinalIgnoreCase) ?? false);
            }

            // 处理 Searchable=true 列与 SeachText 模糊搜索
            if (options.Searchs.Any())
            {
                items = items.Where(options.Searchs.GetFilterFunc<UserListModel>(FilterLogic.Or));
            }
            else
            {
                // 处理 SearchText 模糊搜索
                if (!string.IsNullOrEmpty(options.SearchText))
                {
                    items = items.Where(item => (item.Name?.Contains(options.SearchText) ?? false)
                                                || (item.Name?.Contains(options.SearchText) ?? false));
                }
            }

            // 过滤
            var isFiltered = false;
            if (options.Filters.Any())
            {
                items = items.Where(options.Filters.GetFilterFunc<UserListModel>());
                isFiltered = true;
            }

            // 排序
            var isSorted = false;
            if (!string.IsNullOrEmpty(options.SortName))
            {
                //var invoker = SortLambdaCache.GetOrAdd(typeof(UserTableModel), key => LambdaExtensions.GetSortLambda<UserTableModel>().Compile());
                //items = invoker(items, options.SortName, options.SortOrder);
                isSorted = true;
            }

            // 设置记录总数
            var total = items.Count();

            // 内存分页
            items = items.Skip((options.PageIndex - 1) * options.PageItems).Take(options.PageItems).ToList();

            return Task.FromResult(new QueryData<UserListModel>()
            {
                Items = items,
                TotalCount = total,
                IsSorted = isSorted,
                IsFiltered = isFiltered,
                IsSearch = !string.IsNullOrEmpty(SearchModel.Name) || !string.IsNullOrEmpty(SearchModel.Name)
            });
        }

        [Inject] [NotNull] private ToastService? ToastService { get; set; }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="item"></param>
        private async Task OnRowButtonClick(UserListModel item)
        {
            var cate = ToastCategory.Success;
            var title = "行内按钮处理方法";
            var content = "通过不同的函数区分按钮处理逻辑，参数 Item 为当前行数据";
            await ToastService.Show(new ToastOption()
            {
                Category = cate,
                Title = title,
                Content = content
            });
        }

        #region Service服务调用

        /// <summary>
        /// 添加用户信息
        /// </summary>
        /// <param name="item"></param>
        /// <returns></returns>
        public async Task CreateAsync(UserListModel item)
        {
            await _usersService.CreateAsync(new()
            {
                Name = item.Name,
                Mobile = item.Mobile,
                AccountNo = item.AccountNo,
                PassWord = item.PassWord,
                Integral = item.Integral,
                IsVip = item.IsVip,
                Money = item.Money
            });
        }

        /// <summary>
        /// 加载用户列表
        /// </summary>
        /// <returns></returns>
        public async Task PagingAsync()
        {
            var result = await _usersService.PagingAsync(new()
            {
                PageIndex = 1,
                PageSize = 10
            });

            Items = Mapping.Convert<List<UserListModel>, List<UserPagingResponse>>(result.Data);
        }

        /// <summary>
        /// 删除用户
        /// </summary>
        /// <param name="keyIds"></param>
        public async Task RemoveAsync(Guid[] keyIds)
        {
            await _usersService.RemoveAsync(new()
            {
                KeyIds = keyIds.ToList()
            });
        }

        /// <summary>
        /// 更新用户信息
        /// </summary>
        /// <param name="item"></param>
        public async Task UpdateAsync(UserListModel item)
        {
            var userRequest = Mapping.Convert<UpdateUserRequest, UserListModel>(item);
            await _usersService.UpdateAsync(userRequest);
        }

        #endregion
    }
}